package com.christian.electronic.invoice.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件说明：下载电子发票文件
 *
 * @Author wang
 * @Date 2019/9/27 13:42
 */
@Slf4j
@Service
public class DownloadInvoiceService {

    /**
     * 下载文件
     *
     * @param orderNumber
     * @param response
     * @return
     */
    public boolean downloadInvoice(String orderNumber, HttpServletResponse response) {
        log.info("开始下载文件！");
        //文件路径
        String filePath = "classpath:static/" + orderNumber + ".pdf";

        if (ResourceUtils.isUrl(filePath)) {
            try {
                File file = ResourceUtils.getFile(filePath);

                if (file.exists()) {
                    //设置强制下载不打开
                    response.setContentType("application/force-download;charset=UTF-8");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + new String("啪啪商城电子发票.pdf".getBytes("gb2312"), "ISO8859-1"));
                    response.setCharacterEncoding("UTF-8");

                    byte[] buffer = new byte[1024];
                    FileInputStream fileInputStream = null;
                    BufferedInputStream bufferedInputStream = null;

                    try {
                        fileInputStream = new FileInputStream(file);
                        bufferedInputStream = new BufferedInputStream(fileInputStream);
                        OutputStream outputStream = response.getOutputStream();
                        int i = bufferedInputStream.read(buffer);

                        while (i != -1) {
                            outputStream.write(buffer, 0, i);
                            i = bufferedInputStream.read(buffer);
                        }

                        log.info("文件下载成功！");
                        return true;
                    } catch (IOException e) {
                        log.error(e.getMessage());
                        e.printStackTrace();
                    } finally {
                        try {
                            if (bufferedInputStream != null) {
                                bufferedInputStream.close();
                            }

                            if (fileInputStream != null) {
                                fileInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        log.info("文件下载失败！");

        return false;
    }
}
